package com.gxh.text.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import com.gxh.text.entity.Users;
import com.gxh.text.service.UsersService;

import com.gxh.text.utiles.TokenLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;



@RestController
public class UsersController {
    @Autowired
    private UsersService us;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    @ResponseBody
    public Users Login(String name, String password){

        Users u = us.Login(name,password);
        if (u != null){
            String token = TokenLogin.sign(u.getName(),u.getId());
            Date times =new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");

            if (token != null){
                //在redis里面创建LoginToken键
                redisTemplate.opsForValue();
//              redisTemplate.opsForValue().set("LoginToken",null);
                String o =( String)redisTemplate.opsForValue().get("LoginToken");
                Object parse = JSON.parse(o);
               List parse1=(List)parse;
                List list = JSON.parseObject(o, List.class);//转成对象
                List<String> objects = JSON.parseArray(o, String.class);//list特指

                   List usersList = new ArrayList();


                       usersList.add(token);
                       usersList.add(String.valueOf(u.getId()));
                       usersList.add(String.valueOf(times));
               String jsonArr =JSONArray.toJSONString(usersList);//转成String类型
                       redisTemplate.opsForValue().set("LoginToken",jsonArr);
//                   }



            }
        }
      return u;
    }



}
